package controllers

import (
	"WebSvr/modules/common"
	"WebSvr/modules/memList"
	"WebSvr/modules/mysql"
	"net/http"

	"strconv"
	"text/template"

	"github.com/astaxie/beego"
)

type LoginController struct {
	beego.Controller
}

func (this *LoginController) Get() {
	if !common.GStopFlag {
		this.Data["xsrf_token"] = this.XSRFToken()
		tokenMgr := memList.GetTokenMgr()
		tokenstr := tokenMgr.GeneralToken(common.CMD_LOGIN)
		this.Data["Token"] = tokenstr
		this.TplName = "login.html"
	} else {
		this.CustomAbort(http.StatusBadRequest, "服务器关机中")
	}
}

func (this *LoginController) PostAdminLogin() {
	if !common.GStopFlag {
		//检查传来的token是否存在
		tokenAuthC2S := this.Input().Get("authtoken")
		userNameC2S := this.Input().Get("username")
		passwdC2S := this.Input().Get("password")
		ip := this.Ctx.Input.IP()
		/*转换预防XSS*/
		tokenEscape := template.JSEscapeString(tokenAuthC2S)
		userNameEscape := template.JSEscapeString(userNameC2S)
		passwdEscape := template.JSEscapeString(passwdC2S)
		tokenMgr := memList.GetTokenMgr()
		bAuth := tokenMgr.GetToken(common.CMD_LOGIN, tokenEscape)
		bIp := this.checkUserIpCfg(userNameEscape, ip)
		if bAuth && bIp {
			//验证密码
			webAdmin := mysql.GetWebAdmin()
			bPasswd, authUser := webAdmin.AuthUserLogin(userNameEscape, tokenEscape, passwdEscape, ip)
			if bPasswd {
				accessStr := strconv.Itoa(authUser.Access)
				RecordUserAction(userNameEscape, authUser.Access, ip, "登录后台")
				//成功删除token
				tokenMgr.DelToken(tokenEscape)
				this.CustomAbort(http.StatusOK, accessStr)
				return
			}
		}
		this.CustomAbort(http.StatusUnauthorized, "login auth err")
	} else {
		this.CustomAbort(http.StatusBadRequest, "服务器关机中")
	}
}

func (this *LoginController) checkUserIpCfg(userName string, ip string) bool {
	webAdmin := mysql.GetWebAdmin()
	return webAdmin.CheckUserIpCfg(userName, ip)
}

//检查登录权限 "/loginAccess"
func (this *LoginController) GetAccessByip() {
	if !common.GStopFlag {
		ip := this.Ctx.Input.IP()
		webAdmin := mysql.GetWebAdmin()
		userName, accessInt := webAdmin.GetAccessByIp(ip)

		type LoginData struct {
			Name   string `json:"name"`
			Access int    `json:"access"`
		}
		var loginData LoginData
		loginData.Name = userName
		loginData.Access = accessInt
		this.Data["json"] = loginData
		this.ServeJSON()
	} else {
		this.CustomAbort(http.StatusBadRequest, "服务器关机中")
	}
}

func (this *LoginController) GetLogOut() {
	if !common.GStopFlag {
		ip := this.Ctx.Input.IP()
		webAdmin := mysql.GetWebAdmin()
		userName, access, bsucc := webAdmin.LogOut(ip)
		if bsucc {
			RecordUserAction(userName, access, ip, "登出成功")
		} else {
			RecordUserAction("", access, ip, "登出失败")
		}

		this.Get()
	} else {
		this.CustomAbort(http.StatusBadRequest, "服务器关机中")
	}
}

func (this *LoginController) Finish() {
	requestbody := this.Ctx.Request.Body
	if requestbody != nil {
		defer requestbody.Close()
	}
}
